package com.liuqi.iot.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liuqi.iot.bean.dto.AlarmCategoryDTO;
import com.liuqi.iot.bean.dto.AlarmDTO;
import com.liuqi.iot.bean.dto.DeviceCategoryDTO;
import com.liuqi.iot.bean.dto.DeviceModelDTO;
import com.liuqi.iot.bean.query.AlarmQuery;
import com.liuqi.iot.vo.AlarmVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 报警服务
 *
 * @author  LiuQi 2025/3/25-22:21
 * @version V1.0
 **/
@Service
public class AlarmService {
    @Autowired
    private AlarmEntityService alarmEntityService;

    @Autowired
    private DeviceModelEntityService modelEntityService;

    @Autowired
    private AlarmCategoryEntityService categoryEntityService;

    public IPage<AlarmVO> pageQuery(AlarmQuery query) {
        IPage<AlarmDTO> page = alarmEntityService.pageQuery(query);
        List<AlarmDTO> list = page.getRecords();

        // 补充模型名称及分类名称
        Map<String, String> modelNameMap = new HashMap<>(16);
        Map<String, String> categoryNameMap = new HashMap<>(16);
        if (!CollectionUtils.isEmpty(list)) {
            List<String> modelIds = new ArrayList<>(16);
            List<String> categoryIds = list.stream()
                    .peek(item -> modelIds.add(item.getModelId()))
                    .map(AlarmDTO::getCategoryId)
                    .toList();

            modelNameMap = modelEntityService.findByIds(modelIds)
                    .stream()
                    .collect(Collectors.toMap(DeviceModelDTO::getId, DeviceModelDTO::getName));
            categoryNameMap = categoryEntityService.findByIds(categoryIds)
                    .stream()
                    .collect(Collectors.toMap(AlarmCategoryDTO::getId, AlarmCategoryDTO::getName));
        }

        Map<String, String> pModelNameMap = modelNameMap;
        Map<String, String> pCategoryNameMap = categoryNameMap;
        return page.convert(dto -> {
            AlarmVO vo = new AlarmVO();
            BeanUtils.copyProperties(dto, vo);
            vo.setCategoryName(pCategoryNameMap.get(dto.getCategoryId()));
            vo.setModelName(pModelNameMap.get(dto.getModelId()));
            return vo;
        });
    }

    public Optional<AlarmVO> findById(String id) {
        return alarmEntityService.findById(id)
                .map(dto -> {
                    AlarmVO vo = new AlarmVO();
                    BeanUtils.copyProperties(dto, vo);
                    modelEntityService.findById(dto.getModelId()).ifPresent(model -> vo.setModelName(model.getName()));
                    categoryEntityService.findById(dto.getCategoryId()).ifPresent(category -> vo.setCategoryName(category.getName()));
                    return vo;
                });
    }
}
